package gui.GLListeners;

import java.awt.event.KeyEvent;

import javax.media.opengl.GL;
import javax.media.opengl.GLAutoDrawable;
import javax.media.opengl.GLContext;
import javax.media.opengl.glu.GLU;

public class GLListener2D {
	
	protected double xLeft, xRight, yTop, yBot, xCentro, yCentro;
	private double RatioViewPort;
	private GLU glu;
	private GLContext context;
	
	
	
	public GLListener2D(){
		glu= new GLU();
        xRight=100.0; xLeft=-xRight;
        yTop=100.0; yBot=-xRight;
        xCentro= (xRight+xLeft)/2.0; //=0;
        yCentro= (yTop+yBot)/2.0;    //=0;
        RatioViewPort= 1.0;
	}

	//@Override
	public void display(GLAutoDrawable drw) {
		GL gl = drw.getGL();

        gl.glClear(gl.GL_COLOR_BUFFER_BIT);

        gl.glEnd();
        gl.glFlush();
    }

	//@Override
	public void displayChanged(GLAutoDrawable arg0, boolean arg1, boolean arg2) {
		// TODO Auto-generated method stub

	}

	//@Override
	public void init(GLAutoDrawable drw) {	
		GL gl = drw.getGL();

		gl.glClearColor(1, 1, 1, 0);

        gl.glMatrixMode(GL.GL_PROJECTION);
        gl.glLoadIdentity();
		glu.gluOrtho2D(xLeft,xRight, yBot,yTop);
		
		gl.glMatrixMode(GL.GL_MODELVIEW);
		gl.glLoadIdentity();

		//Animator anim= new Animator(drw);
		//anim.start();

	}

	//@Override
	public void reshape(GLAutoDrawable drw, int x, int y, int width, int height) {
		RatioViewPort= (double)width/(double)height;		
		double RatioVolVista=(xRight-xLeft)/(yTop-yBot);
		
		if (RatioVolVista>=RatioViewPort){
			     //Aumentamos yTop-yBot
			     double altoNew= (xRight-xLeft)/RatioViewPort;
			     yTop= yCentro + altoNew/2.0;
			     yBot= yCentro - altoNew/2.0;
		}
		else{
			//Aumentamos xRight-xLeft
			double anchoNew= RatioViewPort*(yTop-yBot);
			xRight= xCentro + anchoNew/2.0;
			xLeft= xCentro - anchoNew/2.0;
		}

		GL gl = drw.getGL();
		gl.glMatrixMode(GL.GL_PROJECTION);
		gl.glLoadIdentity();
		glu.gluOrtho2D(xLeft,xRight, yBot,yTop);

		gl.glMatrixMode(GL.GL_MODELVIEW);
		gl.glLoadIdentity();
		display(drw);
	}
	
	public void zoom(GLAutoDrawable drw, double factor){
		double newAncho= (xRight-xLeft)*factor;
		double newAlto= (yTop-yBot)*factor;
		xRight= xCentro+newAncho/2.0;
		xLeft= xCentro-newAncho/2.0;
		yTop= yCentro+newAlto/2.0;
		yBot= yCentro-newAlto/2.0;

		GL gl = drw.getGL();

		gl.glMatrixMode(GL.GL_PROJECTION);
		gl.glLoadIdentity();
		glu.gluOrtho2D(xLeft,xRight, yBot,yTop);
		
		//display(drw);
	}
	
	public void keyPressed(KeyEvent arg0) {
		// TODO Auto-generated method stub
		
	}

	public void keyReleased(KeyEvent arg0) {
		// TODO Auto-generated method stub
		
	}

	public void keyTyped(KeyEvent arg0) {
		// TODO Auto-generated method stub
		
	}

}
